package com.cloud.common.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UKTools {

	public static SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

	public static SimpleDateFormat dayFormat = new SimpleDateFormat("yyyyMMdd");

	public static SimpleDateFormat timeRangeDateFormat = new SimpleDateFormat("HH:mm");


	public static String getUUID() {
		return UUID.randomUUID().toString().replace("-", "");
	}

	public static String getContextID(String session) {
		return session.replaceAll("-", "");
	}


	public static long ipToLong(String ipAddress) {
		long result = 0;
		String[] ipAddressInArray = ipAddress.split("\\.");
		if (ipAddressInArray != null && ipAddressInArray.length == 4) {
			for (int i = 3; i >= 0; i--) {
				long ip = Long.parseLong(ipAddressInArray[3 - i]);

				// left shifting 24,16,8,0 and bitwise OR

				// 1. 192 << 24
				// 1. 168 << 16
				// 1. 1 << 8
				// 1. 2 << 0
				result |= ip << (i * 8);

			}
		}
		return result;
	}

	public static String longToIp2(long ip) {

		return ((ip >> 24) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + (ip & 0xFF);
	}

	/***
	 * ID编码 ， 发送对话的时候使用
	 * 
	 * @param id
	 * @param nid
	 * @return
	 */
	public static String genNewID(String id, String nid) {
		StringBuffer strb = new StringBuffer();
		if (id != null && nid != null) {
			int length = Math.max(id.length(), nid.length());
			for (int i = 0; i < length; i++) {
				if (nid.length() > i && id.length() > i) {
					int cur = (id.charAt(i) + nid.charAt(i)) / 2;
					strb.append((char) cur);
				} else if (nid.length() > i) {
					strb.append(nid.charAt(i));
				} else {
					strb.append(id.charAt(i));
				}
			}
		}
		return strb.toString();
	}


	/**
	 * 获取一天的开始时间
	 * 
	 * @return
	 */
	public static Date getStartTime() {
		Calendar todayStart = Calendar.getInstance();
		todayStart.set(Calendar.HOUR_OF_DAY, 0);
		todayStart.set(Calendar.MINUTE, 0);
		todayStart.set(Calendar.SECOND, 0);
		todayStart.set(Calendar.MILLISECOND, 0);
		return todayStart.getTime();
	}

	/**
	 * 获取一天的开始时间
	 * 
	 * @return
	 */
	public static Date getWeekStartTime() {
		Calendar weekStart = Calendar.getInstance();
		weekStart.set(weekStart.get(Calendar.YEAR), weekStart.get(Calendar.MONDAY),
				weekStart.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
		weekStart.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		return weekStart.getTime();
	}

	/**
	 * 获取一天的开始时间
	 * 
	 * @return
	 */
	public static Date getLast30Day() {
		Calendar todayStart = Calendar.getInstance();
		todayStart.set(Calendar.DAY_OF_MONTH, -30);
		todayStart.set(Calendar.HOUR_OF_DAY, 0);
		todayStart.set(Calendar.MINUTE, 0);
		todayStart.set(Calendar.SECOND, 0);
		todayStart.set(Calendar.MILLISECOND, 0);
		return todayStart.getTime();
	}

	public static String getDay() {
		return dayFormat.format(new Date());
	}

	/**
	 * 获取一天的开始时间
	 * 
	 * @return
	 */
	public static Date getLastDay(int days) {
		Calendar todayStart = Calendar.getInstance();
		todayStart.set(Calendar.DAY_OF_MONTH, -days);
		todayStart.set(Calendar.HOUR_OF_DAY, 0);
		todayStart.set(Calendar.MINUTE, 0);
		todayStart.set(Calendar.SECOND, 0);
		todayStart.set(Calendar.MILLISECOND, 0);
		return todayStart.getTime();
	}

	/**
	 * 获取一天的结束时间
	 * 
	 * @return
	 */
	public static Date getEndTime() {
		Calendar todayEnd = Calendar.getInstance();
		todayEnd.set(Calendar.HOUR_OF_DAY, 23);
		todayEnd.set(Calendar.MINUTE, 59);
		todayEnd.set(Calendar.SECOND, 59);
		todayEnd.set(Calendar.MILLISECOND, 999);
		return todayEnd.getTime();
	}

	/**
	 * 获取一天的结束时间
	 * 
	 * @return
	 */
	public static Date getLastTime(int secs) {
		Calendar todayEnd = Calendar.getInstance();
		todayEnd.add(Calendar.SECOND, secs * -1);
		return todayEnd.getTime();
	}


	public static Map<String, Object> transBean2Map(Object obj) {

		if (obj == null) {
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();

				// 过滤class属性
				if (!key.equals("class")) {
					// 得到property对应的getter方法

					Method readMethod = property.getReadMethod();

					if (readMethod != null) {
						Object value = readMethod.invoke(obj);
						if (value instanceof Date) {
							value = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) value);
						}
						map.put(key, value);
					}
				}
			}
		} catch (Exception e) {
			System.out.println("transBean2Map Error " + e);
		}

		return map;

	}


	public static byte[] toBytes(Object object) throws Exception {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ObjectOutputStream objectOutput = new ObjectOutputStream(out);
		objectOutput.writeObject(object);
		return out.toByteArray();
	}

	public static Object toObject(byte[] data) throws Exception {
		ByteArrayInputStream input = new ByteArrayInputStream(data);
		ObjectInputStream objectInput = new ObjectInputStream(input);
		return objectInput.readObject();
	}


	public static String getTopic(String snsid, String msgtype, String eventype) {
		StringBuffer strb = new StringBuffer();
		strb.append(snsid);
		strb.append(".").append(msgtype);
		if (msgtype.equals("text")) {
			strb.append(".").append(msgtype);
		} else if (msgtype.equals("event")) {
			strb.append(".").append(eventype.toLowerCase());
		} else {
			strb.append(".").append(msgtype);
		}
		return strb.toString();
	}


	public static String processEmoti(String message) {
		Pattern pattern = Pattern.compile("\\[([\\d]*?)\\]");
		Matcher matcher = pattern.matcher(message);
		StringBuffer strb = new StringBuffer();
		while (matcher.find()) {
			matcher.appendReplacement(strb,
					"<img src='/im/js/kindeditor/plugins/emoticons/images/" + matcher.group(1) + ".png'>");
		}
		if (strb.length() == 0) {
			strb.append(message);
		}
		return strb.toString();
	}

	/**
	 * 16进制字符串转换为字符串
	 * 
	 * @param s
	 * @return
	 */
	public static String string2HexString(String strPart) {
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < strPart.length(); i++) {
			int ch = (int) strPart.charAt(i);
			String strHex = Integer.toHexString(ch);
			hexString.append(strHex);
		}
		return hexString.toString();
	}

	public static Object json(Object data) {
		return data;
	}
}
